package app;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.menhoo.toollibrary.common.assist.Check;
import com.example.menhoo.toollibrary.common.helper.ExitAppUtil;
import com.example.menhoo.toollibrary.common.helper.MessageUtil;
import com.lidroid.xutils.bitmap.BitmapGlobalConfig;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.util.LogUtils;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import application.AppApplication;
import application.HttpUrlConstant;
import interfaces.IReturnObject;
import mainUI.AppActivity;
import menhoo.com.i8officelibrary.R;
import model.AppModel;
import model.TabModel;

/**
 * 应用列表
 * Created by yanglei on 15/11/1.
 */

public class AppSet extends AppActivity {

    LinearLayout linearLayoutMainMenu;

    LinearLayout ripple_default;

    LinearLayout ripple_apply;

    List<View> viewList;
    int currSelectViewIndex = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.app_set);
        try{
            linearLayoutMainMenu = (LinearLayout)findViewById(R.id.linearLayoutMainMenu);
            ripple_default = (LinearLayout)findViewById(R.id.ripple_default);
            ripple_apply = (LinearLayout)findViewById(R.id.ripple_apply);
            ripple_apply.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try{
//            JSONArray jsonArray = new JSONArray();
                        String strArray = "";
                        final List<TabModel> list = new ArrayList();
                        if(getMenuList()!=null){
                            for (TabModel item : getMenuList()) {
                                if (!item.code.equalsIgnoreCase("My") && !item.name.equalsIgnoreCase("我")) {
                                    //不这样做 getDB().save(model); 有可能保存的是TabModel的子类AppModel 保存会有问题
                                    TabModel model = new TabModel();
                                    model.code = item.code;
                                    model.type = item.type;
                                    model.name = item.name;
                                    model.permisson = item.permisson;
                                    model.htmlUrl = item.htmlUrl;
                                    model.iconUrl = item.iconUrl;
                                    model.isShow = item.isShow;

                                    list.add(model);

//                        JSONObject json = new JSONObject();
//                        json.put("Name",model.name);
//                        json.put("Permission",model.permisson==null?"":model.permisson);
//                        jsonArray.put(json);

                                    //
                                    strArray+=","+model.code;
                                }
                            }
                            //
                            if(strArray.length()>0){
                                strArray=strArray.substring(1);
                            }
                            //
                            RequestParams params = new RequestParams();
                            params.addQueryStringParameter("config", strArray.replace("NULL",""));
                            Post(HttpUrlConstant.getWebSiteFullUrl(HttpUrlConstant.SetNavBar), params, new IReturnObject<String>() {
                                @Override
                                public void returnResult(String result) {
                                    if (result != null) {
                                        try {
                                            JSONObject jsonObject = new JSONObject(result);
                                            if (jsonObject.getBoolean("Succeed")) {
                                                //先清空数据库
                                                getDB().deleteAll(TabModel.class);
                                                getDB().saveAll(list);
                                                //
                                                MessageUtil.showShortToast(AppSet.this, "设置成功");
                                                clearIconCache();
                                                ExitAppUtil.getInstance().exitAllActivity();
                                                startActivity(new Intent(AppSet.this, Main.class));
                                            } else {
                                                MessageUtil.showShortToast(AppSet.this, "对不起,设置失败了,请重试...");
                                            }
                                        } catch (Exception e) {
                                            LogUtils.e(e.getMessage() + "");
                                            MessageUtil.showShortToast(AppSet.this, "对不起,设置失败了,请重试...");
                                        }
                                    } else {
                                        MessageUtil.showShortToast(AppSet.this, "设置失败");
                                    }
                                }
                            });

                        }


                    }
                    catch (Exception e){
                        LogUtils.e(e.getMessage() + "");
                    }
                }
            });

            ripple_default.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Post(HttpUrlConstant.getWebSiteFullUrl(HttpUrlConstant.ReSetNavBar), new IReturnObject<String>() {
                        @Override
                        public void returnResult(String result) {
                            if(result!=null){
                                try {
                                    JSONObject jsonObject = new JSONObject(result);
                                    if (jsonObject.getBoolean("Succeed")) {
                                        MessageUtil.showShortToast(AppSet.this, "已成功恢复为系统默认");
                                        clearIconCache();
                                        ExitAppUtil.getInstance().exitAllActivity();
                                        AppApplication.openLogin(AppSet.this);
                                        //startActivity(new Intent(AppSet.this, Login.class));
                                    } else {
                                        MessageUtil.showShortToast(AppSet.this, "对不起,恢复为系统默认失败了,请重试...");
                                    }
                                } catch (Exception e) {
                                    LogUtils.e(e.getMessage() + "");
                                    MessageUtil.showShortToast(AppSet.this, "对不起,恢复为系统默认失败了,请重试...");
                                }
                            }
                            else{
                                MessageUtil.showShortToast(AppSet.this,"恢复为系统默认失败");
                            }
                        }
                    });
                }
            });
        }
        catch (Exception e){
            LogUtils.e(e.getMessage()+"");
        }

        setTitle("应用设置");

        try {
            List<TabModel> mainTabModelList = getDB().findAll(Selector.from(TabModel.class).orderBy("id", false).limit(4));

            if(mainTabModelList!=null){
                TabModel tabMy = new TabModel();
                tabMy.code="My";
                tabMy.type="internal";
                tabMy.name = "我";
                tabMy.icon = R.mipmap.bottom_nav_4_sel;
                tabMy.permisson = "none";
                mainTabModelList.add(tabMy);
            }

            creatView(mainTabModelList);

        } catch (DbException e) {
            LogUtils.e(e.getMessage()+"");
        }

    }


    void clearIconCache(){
        BitmapGlobalConfig bitmapGlobalConfig = BitmapGlobalConfig.getInstance(this, AppApplication.getAppIconCachePath(this));

        bitmapGlobalConfig.clearMemoryCache();
        bitmapGlobalConfig.clearDiskCache();
        bitmapGlobalConfig.clearCache();
    }


    void creatView(List<TabModel> list){
        //全部清空
        linearLayoutMainMenu.removeAllViews();
        viewList=new ArrayList();

        for(TabModel item :list){
            View view = getLayoutInflater().inflate(R.layout.app_set_item,null);
            view.setTag(item);

            TextView textViewPosition = (TextView)view.findViewById(R.id.textViewPosition);
            Button buttonChange = (Button)view.findViewById(R.id.buttonChange);
            Button buttonDelete = (Button)view.findViewById(R.id.buttonDelete);
            LinearLayout linearLayoutChange =(LinearLayout)view.findViewById(R.id.linearLayoutChange);
            LinearLayout linearLayoutNone =(LinearLayout)view.findViewById(R.id.linearLayoutNone);

            //
            textViewPosition.setText((list.indexOf(item)+1)+"");

            //***
            setAppNameAndImage(view,item);

            if(item.getPermissons()!=null && item.permisson.indexOf("none")>=0){
                linearLayoutChange.setVisibility(View.GONE);
                linearLayoutNone.setVisibility(View.VISIBLE);
            }
            else{
                linearLayoutChange.setVisibility(View.VISIBLE);
                linearLayoutNone.setVisibility(View.GONE);
                final int index = list.indexOf(item);
                buttonChange.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        currSelectViewIndex=index;

                        AppModel appModel = new AppModel();
                        appModel.code="Apps";
                        appModel.type="internal";
                        appModel.name = "应用";

                        Bundle bundle = new Bundle();
                        bundle.putSerializable("MainMenu", getMenuList());

                        Intent it =new Intent(AppSet.this,AutoFragment.class);
                        it.putExtra("Model",appModel);
                        it.putExtra("IsReturnResult",true);
                        it.putExtra("TagBundle",bundle);
                        startActivityForResult(it, Open_Apps);

                    }
                });
                buttonDelete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        clear(index);
                    }
                });
            }

            //加入到页面上
            linearLayoutMainMenu.addView(view);
            viewList.add(view);
        }
    }

    void setAppNameAndImage(View view,TabModel item){

        ImageView imageViewIcon = (ImageView)view.findViewById(R.id.imageViewIcon);
        TextView textViewName = (TextView)view.findViewById(R.id.textViewName);
        LinearLayout linearLayoutApp =(LinearLayout)view.findViewById(R.id.linearLayoutApp);
        LinearLayout linearLayoutEmpty =(LinearLayout)view.findViewById(R.id.linearLayoutEmpty);

        if(item.isShow){
            linearLayoutApp.setVisibility(View.VISIBLE);
            linearLayoutEmpty.setVisibility(View.GONE);

            //如果iconUrl不为空就用iconUrl否则就用icon
            if(Check.isEmpty(item.iconUrl)){
                imageViewIcon.setImageResource(item.icon);
            }
            else{
                getBitmapLoader().display(imageViewIcon, item.iconUrl);
            }
            textViewName.setText(item.name);
        }
        else {
            linearLayoutApp.setVisibility(View.GONE);
            linearLayoutEmpty.setVisibility(View.VISIBLE);
        }
    }

    void clear(String name){
        if(viewList!=null)
        for(View view :viewList){
            if(view!=null){
                TabModel item = (TabModel)view.getTag();

                if(item!=null && item.name.equalsIgnoreCase(name)){
                    int index = viewList.indexOf(view);
                    if(index>=0){
                        clear(index);
                    }

                    return;
                }
            }
        }
    }

    void clear(int viewIndex){
        try{
            View view = viewList.get(viewIndex);
            if(view!=null){
                TabModel item = (TabModel)view.getTag();
                item.isShow=false;
                item.code="";
                item.name="";
                setAppNameAndImage(view,item);
                view.setTag(item);
            }
        }
        catch (Exception e){
            LogUtils.e(e.getMessage()+"");
        }
    }

    ArrayList<TabModel> getMenuList(){
        if(viewList!=null){
            ArrayList<TabModel> list = new ArrayList();
            for(View view : viewList){
                TabModel item = (TabModel)view.getTag();

                list.add(item);
            }
            return list;
        }
        return null;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode== Activity.RESULT_OK && requestCode==Open_Apps){
            try{
                TabModel item = (TabModel)data.getSerializableExtra("Data");
                View view = viewList.get(currSelectViewIndex);
                if(item!=null && view!=null){

                    //看看有没有一样的应用,有的话,清空它
                    clear(item.name);
                    //
                    setAppNameAndImage(view, item);
                    item.isShow=true;
                    view.setTag(item);

                }
            }
            catch (Exception e){
                LogUtils.e(e.getMessage()+"");
            }

        }
    }
}
